﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using BusinessLogic.Security;
using System.ServiceModel;

namespace Otgruzka.Controls.UserAccount
{
    public partial class RoleList : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            BindData();
        }


        protected void gvMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(gvMaster.SelectedRow.Cells[0].Text);

                // Ищется контрол с формой редактирования Центра Затрат и передается ему ID
                var edit = this.Parent.FindControl("RoleEditControl") as RoleEdit;
                if (edit != null)
                {
                    edit.RoleId = id;
                }
            }
            catch (Exception ex)
            { }
        }


        /// <summary>
        /// Клик на кнопке редактирования Центра затрат
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditRoleButton_Click(object sender, ImageClickEventArgs e)
        {
            var button = sender as ImageButton;
            if (button != null)
            {
                if (!string.IsNullOrEmpty(button.CommandArgument))
                {
                    int id = Convert.ToInt32(button.CommandArgument);

                    // Ищется контрол с формой редактирования Центра Затрат и передается ему ID
                    var edit = this.Parent.FindControl("RoleEditControl") as RoleEdit;
                    if (edit != null)
                    {
                        edit.RoleId = id;
                    }
                }
            }
        }

        protected void DeleteRoleButton_Click(object sender, ImageClickEventArgs e)
        {
            var button = sender as ImageButton;
            if (button != null)
            {
                if (!string.IsNullOrEmpty(button.CommandArgument))
                {
                    int id = Convert.ToInt32(button.CommandArgument);

                    var client = new DictionariesClient();
                    try
                    {
                        client.DeleteRole(UserPrincipal.Current.UserId, id);

                        // Ищется контрол с формой редактирования Центра Затрат и передается ему ID
                        var edit = this.Parent.FindControl("RoleEditControl") as RoleEdit;
                        if (edit != null)
                        {
                            edit.RoleId = 0;
                        }
                    }
                    catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
                    {
                        string message = client.GetExceptionDetail(ex);
                        this.ErrorMessage.Text = message;
                        return;
                    }
                    catch (System.Exception exp)
                    {
                        //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Ошибка удаления : " + exp.Message + "');", true);

                        //string message = string.Format("Ошибка удаления: <br />{0}", ExceptionHelper.GetAllMessage(exp));
                        //this.ErrorMessage.Text = message;
                        return;
                    }
                    //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Товар успешно удален.');", true);
                }
            }
        }

        #region Блок кода для NestedGridView

        protected void gvMaster_PreRender(object sender, EventArgs e)
        {
            //foreach (GridViewRow row in gvMaster.Rows)
            //{
            //    ImageButton img = (ImageButton)row.FindControl("imgButSel");
            //    GridView gv = (GridView)row.FindControl("gvChild");
            //    SqlDataSource dsChild = (SqlDataSource)row.FindControl("dsChild");
            //    if (dsChild != null)
            //        dsChild.SelectParameters[0].DefaultValue = row.Cells[3].Text;

            //    if (gv != null)
            //    {
            //        if (!gv.Visible)
            //        {
            //            if (img != null)
            //                img.ImageUrl = "~/images/noselect.gif";
            //        }
            //        else
            //        {
            //            BindChildData(gv);
            //            if (img != null)
            //                img.ImageUrl = "~/images/select.gif";
            //        }
            //    }
            //}
        }

        void BindData()
        {
            var client = new DictionariesClient();
            try
            {
                this.gvMaster.DataSource = client.GetRoleList(UserPrincipal.Current.UserId);
                this.gvMaster.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }

        protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //if (e.CommandName == "InsertNew")
            //{
            //    TextBox tbCatName = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbCategoryName");
            //    TextBox tbDesc = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbDescription");
            //    TextBox tbPictureUrl = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbPictureUrl");

            //    if (tbCatName != null)
            //        dsMaster.InsertParameters["categoryName"].DefaultValue = tbCatName.Text;
            //    if (tbDesc != null)
            //        dsMaster.InsertParameters["description"].DefaultValue = tbDesc.Text;
            //    if (tbPictureUrl != null)
            //        dsMaster.InsertParameters["pictureurl"].DefaultValue = tbPictureUrl.Text;
            //    dsMaster.Insert();
            //    _hfSearch.Value = "";
            //    BindData();
            //}
            //if (e.CommandName == "InsertCancel")
            //{
            //    _hfSearch.Value = "";
            //    BindData();
            //}
        }

        protected void gvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //var dataItem = e.Row.DataItem as ProductsServiceReference.Product;
                //if (dataItem != null)
                //{
                //    var hlBigImage = e.Row.FindControl("hlBigImage") as HyperLink;
                //    if (hlBigImage != null && !string.IsNullOrEmpty(dataItem.ImageBigUrl)) hlBigImage.NavigateUrl = (dataItem.ImageBigUrl[0] != '~') ? string.Format("~{0}", dataItem.ImageBigUrl) : dataItem.ImageBigUrl;

                //    var SmallImage = e.Row.FindControl("SmallImage") as Image;
                //    if (SmallImage != null && !string.IsNullOrEmpty(dataItem.ImageSmallUrl)) SmallImage.ImageUrl = (dataItem.ImageSmallUrl[0] != '~') ? string.Format("~{0}", dataItem.ImageSmallUrl) : dataItem.ImageSmallUrl;
                //}

                //var bgarr = Array("White", "#DdDdDd", "#6b8cbe", "red");

                e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#6b8cbe'";
                e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white'";
                e.Row.Attributes["style"] = "cursor:hand;";

                var grid = sender as SamApp.WebControls.NestableGridView;
                string postback = Page.ClientScript.GetPostBackEventReference(grid, string.Format("Select${0}", e.Row.RowIndex));
                e.Row.Attributes.Add("onclick", postback.ToString());
            }
        }

        #endregion Блок кода для NestedGridView

    }
}